package com.gcosc.hly.codejava.filter;


import com.gcosc.hly.codejava.Utils.TokenUtils;
import com.gcosc.hly.codejava.result.Code;
import com.gcosc.hly.codejava.result.Token;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class IPHandlerInterceptor implements HandlerInterceptor {

//    private final IPService ipService;
    private final TokenUtils tokenUtil;
    @Value("${token.privateKey}")
    private String privateKey;
    @Value("${token.yangToken}")
    private Long yangToken;
    @Value("${token.oldToken}")
    private Long oldToken;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                             Object object) throws Exception {
//        if (ipService.ifIPAddress(httpServletRequest, httpServletResponse)){
//            httpServletResponse.setStatus(403);
//            return false;
//        }

        AuthRoot methodAnnotation = null;

        if (object instanceof HandlerMethod){
            HandlerMethod h = (HandlerMethod)object;
            methodAnnotation = h.getMethod().getAnnotation(AuthRoot.class);
        }


        String token = httpServletRequest.getHeader("token");
        if (null == token || "".equals(token)) {
            if (methodAnnotation == null){
                return true;
            }
            Code.TOKEN_ERR("请先登录！");
        }

        Token tok = tokenUtil.parseToken(token);

        httpServletRequest.setAttribute("token", tok);
        long timeOfUse = System.currentTimeMillis() - tok.getTime();
        if (timeOfUse >= yangToken && timeOfUse < oldToken) {
            httpServletResponse.setHeader("Access-Control-Expose-Headers" , "token");
            httpServletResponse.setHeader("token",tokenUtil.getToken(tok.getId(),tok.getRoot()));
        } else if (timeOfUse >= oldToken){
            Code.TOKEN_ERR("登陆已过期，请重新登陆");
        }

        if (methodAnnotation != null && tok.getRoot() < methodAnnotation.value().getValue()){
            Code.TOKEN_AUTH_ERR();
        }

//        if (loginService.isLoginTime(new Date(Long.parseLong(map.get("timeStamp"))))){
//            throw new TokenAuthExpiredException("其他设备登陆了你的账户，请重新登陆");
//        }

        return true;
    }
}
